<?php

namespace App\Http\Controllers;

use App\Models\Sendlist;
use App\Models\Sites;
use Illuminate\Http\Request;
use App\Models\Word;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Image;

class ApiController extends Controller
{
    /**
     * 单词接口返回数据
     * @param [type] $word
     * @return void
     */
    public function sendWord(Request $request)
    {
        DB::beginTransaction();
        try {
            $site = session('site');
//            $site = Sites::find(2);
            $where['sites_id'] = $site['id'];
            $where['is_out'] = 0;     //未过期
//            $where['is_send'] = 0;    //未发送

            //当天0点开始，次日0点结束
            $start = strtotime(date("y-m-d", time()));
            $deadline = $start + 3600 * 24;
//            $sendlist = Sendlist::where($where)->where('publish_time', '>=', $start)->where('publish_time', '<', $deadline)->first();
            $sendlist = Sendlist::where($where)->where('publish_time', '<', $start)->first();
            //如果没有数据，则返回null
            if (!$sendlist) {
                return response()->json(['status' => true, 'data' => null]);
            }
            $words = $startends = [];
            $url = $request->getUri();
            $pop = array_slice(explode('/', $url), 0, 3);
            $url = implode('/', $pop);
            //获取单词相关数据
            if ($sendlist['lastid']) {
                $words = $sendlist['category']['words']->where('id', '>', $sendlist['lastid'])->take(10)->toArray();
            } else {
                $words = $sendlist['category']['words']->take(10)->toArray();
            }
            //最后一条数据id
            $words = array_values($words);
            $lastid = $words[count($words) - 1]['id'];
            foreach ($words as $key => $word) {
                $word['logo'] = $url . '/lookup/' . $word['word'];
                $word['logo'] .= '?watermark=' . substr($site['watermark'], 1) . '&bgcolor=' . $site['bgcolor'];
                $word['template'] = $site['template'];
                $sentences = json_decode($word['sentences'], true);
                shuffle($sentences);
                $temp_arr = [];
                foreach ($sentences as $skey => $sentence) {
                    if ($skey < 6) {
                        $temp_arr[] = $sentence;
                    } else {
                        break;
                    }
                }
                $word['sentences'] = json_encode($temp_arr);
                //删除多余字段
                unset($word['id'], $word['pivot'], $word['created_at']);
                $words[$key] = $word;
            }


            //查出关联站点下的开头结尾
            $startends = $site['startends']->toArray();
            foreach ($site['startends'] as $skey => $start) {
                //删除多余字段
                unset($startends[$skey]['id'], $startends[$skey]['created_at'], $startends[$skey]['updated_at'], $startends[$skey]['sites_id']);
            }
            //组装返回值
            $datas = ['words' => $words, 'startends' => $startends];
            return response()->json(['status' => true, 'sendlist_id' => $sendlist['id'], 'lastid' => $lastid, 'data' => $datas]);
        } catch (\Exception $e) {
            return response()->json(['status' => false, 'data' => null]);
        }
    }

    /**
     * 站点发送成功后，异步请求更改队列状态
     */
    public function editList(Request $request)
    {
        $sendlistid = $request->sendlistid;
        $lastid = $request->lastid;
        if ($sendlistid) {
            cache(['sendsuccess' => session('site.name') . '数据接收成功！时间：' . date("Y-m-d H:i:s", time())], 10);
            //查找队列数据
            $sendlist = Sendlist::find($sendlistid);
            $last_id = $sendlist['category']['words'][count($sendlist['category']['words']) - 1]['id'];
            if ($lastid == $last_id) {
                $save['is_out'] = 1;  //分类最后一个单词，终止
                $content = "站点：&nbsp;【" . $sendlist['site']['url'] . "】&nbsp;&nbsp;<br>分类：&nbsp;【" . $sendlist['category']['name'] . "】下的单词已发完！<br>时间：&nbsp;" . date("Y-m-d H:i:s", time());
                $to = "liqi@ekewo.org";
                //发送邮件
                Mail::send('layouts.email', ['content' => $content], function ($message) use ($to) {
                    $message->from(config()->get('mail.username'), '单词发文api');
                    $message->to($to)->subject('【单词发文api】队列单词已发完');
                });
            }
            $save['is_send'] = 1;   //已发送
            $save['lastid'] = $lastid;
            //更改队列状态为已发送
            $sendlist->update($save);
            return ['status' => true, 'msg' => 'success'];
        }
        return ['status' => true, 'msg' => 'outside'];
    }

    public function errjson($msg = '出错了！')
    {
        return response()->json(['status' => false, 'msg' => $msg]);
    }

    /**
     * 单词生成图片
     * @param $word 单词
     * @param $watermark 水印图片
     * @param $color 字体颜色
     * @param $bgcolor 图片背景颜色
     */
    public function wordImage($word, Request $request)
    {
//        $watermark = "uploads/upload/sy.png";
        //查找单词
        $wordinfo = Word::where('word', $word)->first();

        //字体颜色
        $color = "#fff";

        //生成画布
//        $bgcolor = "#ea5317";
        $bgcolor = $request->bgcolor;
        $img = $bgcolor == "" ? Image::canvas(600, 372) : Image::canvas(600, 372, "#" . $bgcolor);

        //插入水印
        if ($request->watermark) {
            $watermark = $request->watermark;
            $img->insert($watermark, 'bottom-right');
        }

        //单词
        $img->text($wordinfo->word, 60, 80, function ($font) use ($color) {
            $ft = public_path('fonts/lingoes.ttf');
            $font->file($ft);
            $font->size(70);
            $font->color($color);
            $font->align('left');
//            $font->valign('top');
            $font->angle(0);
        });
        //处理音标
        $pron = json_decode($wordinfo['pron'], true);
        $pruk = $pron['pruk'] ? "US:" . substr($pron['pruk'], 3) . "\n\r" : "";
        $prus = $pron['prus'] ? "UK:" . substr($pron['prus'], 3) : "";
        $soundmark = $pruk . $prus;
        $img->text($soundmark, 60, 175, function ($font) use ($color) {
            $ft = public_path('fonts/lingoes.ttf');
            $font->file($ft);
            $font->size(30);
            $font->color($color);
            $font->align('left');
//            $font->valign('top');
            $font->angle(0);
        });
        //处理释义
        $interprets = json_decode($wordinfo['interpret'], true);
        $theone = '';
        foreach ($interprets as $inter) {
            if (strlen($inter['def']) > 81) {
                $inter['def'] = substr($inter['def'], 0, 81) . '...';
            }
            $theone .= $inter['pos'] . $inter['def'] . "\n\r";
        }
        $img->text($theone, 60, 220, function ($font) use ($color) {
            $ft = public_path('fonts/fangzheng.ttf');
            $font->file($ft);
            $font->size(15);
            $font->color($color);
            $font->align('left');
            $font->valign('top');
            $font->angle(0);
        });
        return $img->response('png', 70);
    }
}
